package net.csdra.DongPoShuZiTuShuGuan.service;

import net.csdra.DongPoShuZiTuShuGuan.domain.PlayInfo;
import net.csdra.DongPoShuZiTuShuGuan.domain.PlayInfoRepository;
import net.csdra.DongPoShuZiTuShuGuan.domain.Video;
import net.csdra.DongPoShuZiTuShuGuan.domain.VideoRepository;
import net.csdra.DongPoShuZiTuShuGuan.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.List;

/**
 * Created by add on 2018/1/17.
 */
@Service
public class VideoServiceImpl implements VideoService {


    VideoRepository videoRepository;

    PlayInfoRepository playInfoRepository;

    @Autowired
    public VideoServiceImpl(VideoRepository videoRepository, String videoUrl, String videoName, String videoInfo, PlayInfoRepository playInfoRepository) {
        this.videoRepository = videoRepository;
        this.playInfoRepository = playInfoRepository;
        if (this.videoRepository.count() < 1) {
            Video v = Utils.createAutoSet(Video.class, "system");
            v.setInfo(videoInfo);
            v.setName(videoName);
            v.setVideoUrl(videoUrl);
            this.videoRepository.save(v);
            PlayInfo playInfo = Utils.createAutoSet(PlayInfo.class, "system");
            playInfo.setVideoId(v.getId());
            this.playInfoRepository.save(playInfo);
        }
    }

    @Override
    public Video getVideo() {
        return this.videoRepository.findByEnabledAndDeleted(true, false);
    }

    @Override
    public Page<Video> getVideoByState(GetVideoByState getVideoByState) {
        Assert.notNull(getVideoByState, "参数不能为空");
        return this.videoRepository.findByEnabledAndDeleted(getVideoByState.getEnable(), false,
                new PageRequest(getVideoByState.getPage(), getVideoByState.getSize(), Sort.Direction.ASC, "lastModifiedTime"));
    }

    @Override
    public Video getPlayVideo() {
        List<PlayInfo> playInfos = this.playInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
            return criteriaQuery.orderBy(criteriaBuilder.asc(root.get("createTime"))).getRestriction();
        });
        Assert.state(playInfos.size() > 0, "@未设置在播视频");
        Video one = this.videoRepository.findOne(playInfos.get(0).getVideoId());
        return one;
    }
}
